
local Tool=require(script.Parent.tool)
local SocialService=game:GetService("SocialService")

local function_list =_G.ClientOHOH.function_list
local M=_G.ClientOHOH.class.new(script, _G.ClientOHOH.files.Client_PlayerComponent(),script.Parent.Name);
local BroGui= _G.ClientOHOH.load.UIManager():CreateUI("BroGui",require(script.BroGui))
local PlayerInfoHelper=_G.ClientOHOH.load.PlayerInfoHelper()
local LanguageHelper= _G.LanguageHelper

local slotGoodsCfg=_G.CommonOHOH.config.Goods[810]
local Game_Cfg=_G.CommonOHOH.config.Game

local WeaponTool=_G.CommonOHOH.load.WeaponTool();


function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);	

    self.BroCharacterList={}
    self.player=self.parent
    self.Bro={}
    self.DataStore=self.parent:GetComponent(_G.ClientOHOH.load.Client_PlayerDataComponent())

    self.parent:AddPrivateComponent(script.SeekFriendCtrl)


    _G.ClientOHOH.load.UIManager().ui_list.HomeGui:SetFriendEquipRed() --初始化，屏蔽小红点
    self:Update(self.DataStore:GetData("bro"))
    BroGui:ActiveFristBro() --默认选中第一个

    self.parent.UserDataEvent:Connect(function(data)
        if data["bro"] then
            self:Update(self.DataStore:GetData("bro"))
        elseif data["broEquip"]  then
            self:Update(self.DataStore:GetData("bro"))
        elseif data["base"]  then
            BroGui:UpdateMeatCount(data["base"].meat)
        end;
    end);

    BroGui:UpdateMeatCount(self.DataStore:GetData("base").meat)

    --售卖
    BroGui.SellEvent:Connect(function(idList)
        self:Sell(idList)
   end)

    --装备
    BroGui.EquipEvent:Connect(function(idList)
        -- _G.ClientOHOH:PrintTable(idList)
        self:Equip(idList)
   end)

    --升级
    BroGui.UpgradeEvent:Connect(function(idList)
        return   self:Upgrade(idList)
   end)

    --装备最佳
    BroGui.BestEquipEvent:Connect(function()
        self:EquipBest()
    end)

    --卸载所有
    BroGui.UnEquipAllEvent:Connect(function()
        self:UnEquipAll()
    end)

    --卸载某一个
    BroGui.UnEquipEvent:Connect(function(idList)
        self:UnEquip(idList)
    end)

    --购买槽位
    BroGui.BuyEquipSlotsEvent:Connect(function()
       -- 购买槽位
       self.player.RobuxBuyEvent:Action(slotGoodsCfg.id)
    end)

    self.player.CanNotRobuxBuyEvent:Connect(function(gid,gtype,...)
        if gid==slotGoodsCfg.id then
            if self.DataStore:GetData("bro").slot>Game_Cfg.FriendSlots then
                return  true
            end
        end
    end)


    
     if self.player.character then
        self.player.character:AddPrivateComponent(script.l)
    end

    self.player.CharacterEnterEvent:Connect(function(character)
            character:AddPrivateComponent(script.BroView)
    end)

end;

function M.dtor(self)
	M.super.dtor(self);
end;

function M.FindWeaponId(self,broId)
    -- print("_____AAAAA_______FindWeaponId_____",broId)
   local weaponId= self.DataStore:GetData("broEquip")[broId]
--    print("_____AAAAA_______FindWeaponId_____",broId,weaponId)

   if weaponId then

        return weaponId
   end
   return "1_1"
end

function M.CreateOne(self,k,bro,equipId)
    local BroObject={
        id=k,
        isEquip=false,
        userId=bro.userId,
        isLock=false,--是否锁定
        level=1,--等级
        headIcon="---AAA-",
        name="yzyzbobo",
        wpn=0, --武器攻击力
        atk=0,--自身攻击力
        nextAtk=0,--下一等级攻击力
        weaponId="1_1",--携带武器
        UpdateEvent=_G.CommonOHOH.load.Connect().new(),
        DtorEvent=_G.CommonOHOH.load.Connect().new(),

        Update=function(this,data,eid)

            this:equipUpd(eid)
            local calculate=Tool.Calculate(data)
            if data.lock==1 then
                this.isLock=true
            else
                this.isLock=false
            end
          
            this.level=data.level
            this.showLevel=Tool.Calculate_cfg_level(data.baseLevel,data.level)
            this.baseLevel=data.baseLevel
            this.atk=calculate.power
            this.sell=calculate.sell
            this.nextAtk=calculate.nextPower
            this.upgrade=calculate.upgrade
            this.weaponId=self:FindWeaponId(this.id)
            this.wpn= WeaponTool.Calculate_power(this.weaponId)

            this.UpdateEvent:Action()

        end,
        

         equipUpd=function(this,eid)
            local isequip=false
            for _,v in pairs(eid) do
                if  v ==this.id then
                    isequip=true
                    break
                end
            end
            this.isEquip=isequip

        end,

        UpdateEquip=function(this,eid)
            this:equipUpd(eid)
            this.UpdateEvent:Action()
        end,
        UpdateLock=function(this,v)
            this.lock=v
            this.UpdateEvent:Action()
        end,

        dtor=function(this)
              this.DtorEvent:Action()

              this.UpdateEvent:dtor()
              this.DtorEvent:dtor()
        end,

        findCharacter=function(this)
           return  self:GetCharacter(this.userId)
        end,

    }
    BroObject:Update(bro,equipId)
    BroGui:AddData(BroObject)

    PlayerInfoHelper.GetPlayerInfo(bro.userId,function(h,n)
        BroObject.headIcon=h
        BroObject.name=n
        BroObject.UpdateEvent:Action()
	end)

        --更新主界面小红点
     _G.ClientOHOH.load.UIManager().ui_list.HomeGui:SetFriendEquipRed(1)

    return BroObject
end



function M.Update(self,bro)
    -- print("------Update-----bro------AAA--")
    -- _G.CommonOHOH:PrintTable(bro)
    local had=bro.had
    local equip=bro.equip
    local hadList={}
    for k,v in pairs(had) do
        hadList[k]=true
        if self.Bro[k] then
            self.Bro[k]:Update(v,equip)
          
        else
            self.Bro[k]=self:CreateOne(k,v,equip)
        end
    end

    for k,v in pairs(self.Bro) do
        if not hadList[k] then
            v:dtor()
            self.Bro[k]=nil               
        end
    end
    local a,b=self:GetSolt()
    local c=false
    if b>Game_Cfg.FriendSlots then --已经大于默认槽位了，不能购买
        c=true
    end
    BroGui:UpdateSlot(a,b,c)
end



function M.GetBro(self)
    return self.Bro
end


-----------------服务器接口--------------------------------


--装备最佳好友：
-- 返回值：true，成功，false 失败
function M.EquipBest(self) 
    
    if  not self:isInCd() then
        return 
    end

   return self:Invoke(function_list.bro_operate,"EquipBest")

    -- _G.ClientOHOH:PrintTable(equip)


    -- if equip then
    --     self:UpdateBro(nil,equip)
    --    return true
    -- else
    --     return false
    -- end
end

-- 卸载所有好友：
-- 返回值：true，成功，false 失败
function M.UnEquipAll(self) 
    
    if  not self:isInCd() then
        return 
    end

    return    self:Invoke(function_list.bro_operate,"UnEquipAll")

    -- local isDone= self:Invoke(function_list.bro_operate,"UnEquipAll")
    -- if isDone then
    --     self:UpdateBro(nil,{})
    --    return true
    -- else
    --     return false
    -- end
end

--卸载好友:idList,传一个数组，如：{1，2，3}，
-- 返回值：true，成功，false 失败
function M.UnEquip(self,idList)
    
    if  not self:isInCd() then
        return 
    end


    return self:Invoke(function_list.bro_operate,"UnEquip",idList)
    -- local equip= self:Invoke(function_list.bro_operate,"UnEquip",idList)
    -- if equip then
    --     self:UpdateBro(nil,equip)
    --    return true
    -- else
    --     return false
    -- end
end

--装备好友:idList,传一个数组，如：{1，2，3}，
-- 返回值：true，成功，false 失败，如果返回值是false，会附带错误码-> 1：槽位已经满，2，去购买槽位，3 未知错误
function M.Equip(self,idList)

    if  not self:isInCd() then
        return 
    end


    local errorCode=Tool.IsCanEquip(idList,self.DataStore:GetData("bro").equip,self.DataStore:GetData("bro").slot)
    if  errorCode>0 then
        return false,errorCode
    end

    -- print("-------------function_list.bro_operate,Equip,idList---------------")
    return  self:Invoke(function_list.bro_operate,"Equip",idList)

    -- local equip,errorCode= self:Invoke(function_list.bro_operate,"Equip",idList)
    -- if equip then
    --    self:UpdateBro(nil,equip)
    --    return true
    -- else
    --     return false,errorCode
    -- end
end

-- 售卖好友:idList,传一个数组，如：{1，2，3}
-- 返回值：true，成功，false 失败
function M.Sell(self,idList)

    if  not self:isInCd() then
        return 
    end

    local r= self:Invoke(function_list.bro_operate,"Sell",idList)

    if r then
        _G.GlobalTipGui:Show(LanguageHelper:GetText(8888003))
    end

    return r
    -- local bro= self:Invoke(function_list.bro_operate,"Sell",idList)
    -- if bro then
    --    self:UpdateBro(bro)
    --    return true
    -- else
    --     return false
    -- end
end


function M.isInCd(self)
    if self.lastOpTime and tick()-self.lastOpTime<0.5 then
        return  false
    end
    self.lastOpTime=tick()
    return true
end

-- 保存锁定状态
function M.SaveLockState(self)

    if  not self:isInCd() then
        return 
    end

    local r= self:Invoke(function_list.bro_operate,"SaveLockState",self:GetLockInfo())

    return r
    -- local bro= self:Invoke(function_list.bro_operate,"SaveLockState",self:GetLockInfo())
    -- if bro then
    --     self:UpdateBro(bro)
    --     return true
    --  else
    --      return false
    --  end
end


-- 升级好友:idList,传一个数组，如：{1，2，3}
-- 返回值：true，成功，false 失败， 错误码：1：肉不够，2已经满级，不能升级，3 其它未知原因
function M.Upgrade(self,idList)

    if  not self:isInCd() then
        return false
    end


    local errorCode,sum= Tool.IsCanUpgrade(idList,self.Bro,self.DataStore)

    if errorCode==1 then
        _G.GlobalTipGui:Show(LanguageHelper:GetText(8888009))
        return 
    end
    if  errorCode>0 then
        return false,errorCode
    end

    local r=  self:Invoke(function_list.bro_operate,"Upgrade",idList)

    if r then
        _G.GlobalTipGui:Show(LanguageHelper:GetText(8888003))
    end

    return r

--     local bro,code= self:Invoke(function_list.bro_operate,"Upgrade",idList)
--     -- _G.CommonOHOH:PrintTable(bro)


--     if bro then
--        self:UpdateBro(bro)
--        return true
--     else
--         return false,code
--     end
end


-- 获取好友槽位信息，返回，now, all,当前装备数，和总计可以装备的数量
-- 返回值：当前装备数，可装备的最大数
function M.GetSolt(self)
    return #self.DataStore:GetData("bro").equip,self.DataStore:GetData("bro").slot
end

--能否购买槽位
-- 返回值：true，能，false 不能
function M.IsCanBuySolt(self)
    if  not self:isInCd() then
        return 
    end


    return Tool.IsCanBuySolt(self.DataStore:GetData("bro").slot)
end


--激活某一个好友
function M.Feed(self,userId,guid,chapterId,levelId)
    if  not self:isInCd() then
        return 
    end


    local errorCode,sum= Tool.IsCanAwake(chapterId,levelId,self.DataStore)
    if  errorCode>0 then
        return false,errorCode
    end

    return  self:Invoke(function_list.bro_operate,"Feed",userId,guid,chapterId,levelId)
end

return M